package com.corpgovernment.common.supplier;

import com.corpgovernment.common.apollo.BaseConfig;
import com.ctrip.corp.obt.generic.core.http.HttpResponse;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * 默认的分销错误信息转换器
 *
 * @author xukang zhang
 * @date 2024/2/8 10:29
 */
@Slf4j
public class DefaultResponseConverter<T> extends ResponseConverter<T> {

    /**
     * 默认的代表成功的resultCode（未找到resultCode时使用）
     */
    private static final int DEFAULT_SUCCESS_CODE = 0;
    /**
     * 默认的代表失败的resultCode（解析失败时使用）
     */
    private static final int DEFAULT_ERROR_CODE = Integer.MIN_VALUE;
    /**
     * 默认的message
     */
    private static final String DEFAULT_MESSAGE = "";
    public static final String PATH_SPLIT_SYMBOL = ".";


    public DefaultResponseConverter(Class<T> clazz) {
        super(clazz);
    }

    @Override
    public HttpResponse<T> convertSupplierResponse(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        JsonNode jsonObject = null;
        try {
            jsonObject = JsonUtils.getJsonNode(json);
        } catch (Exception e) {
            log.error("[Error occurs while parsing json from Supplier's Response]", e);
            return null;
        }
        int resultCode = DEFAULT_SUCCESS_CODE;
        Set<String> errorCodePaths = BaseConfig.defaultConfig().supplierErrorCodePaths();
        // 未找到errorCode，则默认为0代表正常响应
        for (String errorCodePath : errorCodePaths) {
            resultCode = findResultCode(jsonObject, errorCodePath);
            if (resultCode != DEFAULT_SUCCESS_CODE) {
                break;
            }
        }
        String message = DEFAULT_MESSAGE;
        Set<String> errorMessagePaths = BaseConfig.defaultConfig().supplierErrorMessagePaths();
        // 未找到errorCode，则默认为0代表正常响应
        for (String errorMessagePath : errorMessagePaths) {
            message = findMessage(jsonObject, errorMessagePath);
            if (!DEFAULT_MESSAGE.equals(message)) {
                break;
            }
        }
        return new HttpResponse<>(resultCode, message);
    }

    /**
     * 从jsonObject中查找path指定字段的代表ResultCode取值
     *
     * @param jsonNode
     * @param path
     * @return
     */
    private static int findResultCode(JsonNode jsonNode, String path) {
        if (jsonNode == null || StringUtils.isBlank(path)) {
            return DEFAULT_SUCCESS_CODE;
        }
        int splitIndex = path.indexOf(PATH_SPLIT_SYMBOL);
        if (splitIndex != -1) {
            // 有子路径，则递归查找json子节点
            String currentField = path.substring(0, splitIndex);
            String childPath = path.substring(splitIndex + 1);
            JsonNode childJsonObject = jsonNode.path(currentField);
            if (childJsonObject.isMissingNode() || childJsonObject.isNull()) {
                return DEFAULT_SUCCESS_CODE;
            }
            return findResultCode(childJsonObject, childPath);
        }
        // 未找到errorCode，则默认为0代表正常响应
        int errorCode;
        // 获取errorCode字段的取值
        JsonNode currentNode = jsonNode.path(path);
        if (currentNode.isMissingNode() || currentNode.isNull()) {
            return DEFAULT_SUCCESS_CODE;
        }
        if (currentNode.isInt()) {
            errorCode = currentNode.asInt();
        } else if (currentNode.isTextual()) {
            String text = currentNode.asText();
            if (StringUtils.isBlank(text)) {
                return DEFAULT_SUCCESS_CODE;
            }
            try {
                errorCode = Integer.parseInt(text);
            } catch (NumberFormatException e) {
                log.error("[Not int value while parsing json from Supplier's Response]", e);
                errorCode = DEFAULT_ERROR_CODE;
            }
        } else {
            errorCode = DEFAULT_ERROR_CODE;
        }
        return errorCode;
    }

    /**
     * 从jsonObject中查找path指定字段的代表Message取值
     *
     * @param jsonNode
     * @param path
     * @return
     */
    private String findMessage(JsonNode jsonNode, String path) {
        if (jsonNode == null || StringUtils.isBlank(path)) {
            return DEFAULT_MESSAGE;
        }
        int splitIndex = path.indexOf(PATH_SPLIT_SYMBOL);
        if (splitIndex != -1) {
            // 有子路径，则递归查找json子节点
            String currentField = path.substring(0, splitIndex);
            String childPath = path.substring(splitIndex + 1);
            JsonNode childJsonObject = jsonNode.path(currentField);
            if (childJsonObject.isMissingNode() || childJsonObject.isNull()) {
                return DEFAULT_MESSAGE;
            }
            return findMessage(childJsonObject, childPath);
        }
        // 未找到message，则默认为""代表正常响应
        String message;
        // 获取errorCode字段的取值
        JsonNode currentNode = jsonNode.path(path);
        if (currentNode.isMissingNode() || currentNode.isNull()) {
            return DEFAULT_MESSAGE;
        }
        message = currentNode.asText(DEFAULT_MESSAGE);
        return message;
    }


    @Override
    protected int convertResultCode(Object response) {
        return 0;
    }

    @Override
    protected String convertMessage(Object response) {
        return null;
    }

}
